<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所在省份" prop="province">
        <el-select v-model="queryParams.province" placeholder="请选择所在省份" clearable @change="handleProvinceChange">
          <el-option
            v-for="dict in dict.type.province"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所在城市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择所在城市" clearable :disabled="!queryParams.province" @change="handleCityChange">
          <el-option
            v-for="city in filteredCityList"
            :key="city.value"
            :label="city.label"
            :value="city.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所在城区/县城" prop="district">
        <el-select v-model="queryParams.district" placeholder="请选择所在城区/县城" clearable :disabled="!queryParams.city">
          <el-option
            v-for="area in filteredAreaList"
            :key="area.value"
            :label="area.label"
            :value="area.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="道路站点名称" prop="roadSiteName">
        <el-input
          v-model="queryParams.roadSiteName"
          placeholder="请输入道路站点名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['parking:site:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['parking:site:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['parking:site:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['parking:site:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="siteList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="所在省份" align="center" prop="province">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.province" :value="scope.row.province"/>
        </template>
      </el-table-column>
      <el-table-column label="所在城市" align="center" prop="city">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.city" :value="scope.row.city"/>
        </template>
      </el-table-column>
      <el-table-column label="所在城区/县城" align="center" prop="district">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.area" :value="scope.row.district"/>
        </template>
      </el-table-column>
      <el-table-column label="道路站点名称" align="center" prop="roadSiteName" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['parking:site:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['parking:site:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改停车道路站点管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所在省份" prop="province">
          <el-select v-model="form.province" placeholder="请选择所在省份" clearable @change="handleFormProvinceChange">
            <el-option
              v-for="dict in dict.type.province"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在城市" prop="city">
          <el-select v-model="form.city" placeholder="请选择所在城市" clearable :disabled="!form.province" @change="handleFormCityChange">
            <el-option
              v-for="city in filteredFormCityList"
              :key="city.value"
              :label="city.label"
              :value="city.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所在城区/县城" prop="district">
          <el-select v-model="form.district" placeholder="请选择所在城区/县城" clearable :disabled="!form.city">
            <el-option
              v-for="area in filteredFormAreaList"
              :key="area.value"
              :label="area.label"
              :value="area.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="道路站点名称" prop="roadSiteName">
          <el-input v-model="form.roadSiteName" placeholder="请输入道路站点名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSite, getSite, delSite, addSite, updateSite } from "@/api/parking/site"
import { getDicts } from "@/api/system/dict/data"

export default {
  name: "Site",
  dicts: ['province', 'city', 'area'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 停车道路站点管理表格数据
      siteList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        province: null,
        city: null,
        district: null,
        roadSiteName: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        province: [
          { required: true, message: "所在省份不能为空", trigger: "change" }
        ],
        city: [
          { required: true, message: "所在城市不能为空", trigger: "change" }
        ],
        district: [
          { required: true, message: "所在城区/县城不能为空", trigger: "change" }
        ],
        roadSiteName: [
          { required: true, message: "道路站点名称不能为空", trigger: "blur" }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  computed: {
    // 根据省份过滤城市（查询表单）
    filteredCityList() {
      if (!this.queryParams.province) {
        return []
      }
      const provinceCode = this.queryParams.province.substring(0, 2)
      return this.dict.type.city.filter(city => city.value.substring(0, 2) === provinceCode)
    },
    // 根据城市过滤区县（查询表单）
    filteredAreaList() {
      if (!this.queryParams.city) {
        return []
      }
      const cityCode = this.queryParams.city.substring(0, 4)
      return this.dict.type.area.filter(area => area.value.substring(0, 4) === cityCode)
    },
    // 根据省份过滤城市（编辑表单）
    filteredFormCityList() {
      if (!this.form.province) {
        return []
      }
      const provinceCode = this.form.province.substring(0, 2)
      return this.dict.type.city.filter(city => city.value.substring(0, 2) === provinceCode)
    },
    // 根据城市过滤区县（编辑表单）
    filteredFormAreaList() {
      if (!this.form.city) {
        return []
      }
      const cityCode = this.form.city.substring(0, 4)
      return this.dict.type.area.filter(area => area.value.substring(0, 4) === cityCode)
    }
  },
  methods: {
    /** 查询停车道路站点管理列表 */
    getList() {
      this.loading = true
      listSite(this.queryParams).then(response => {
        this.siteList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 查询表单省份变化 */
    handleProvinceChange() {
      this.queryParams.city = null
      this.queryParams.district = null
    },
    /** 查询表单城市变化 */
    handleCityChange() {
      this.queryParams.district = null
    },
    /** 编辑表单省份变化 */
    handleFormProvinceChange() {
      this.form.city = null
      this.form.district = null
    },
    /** 编辑表单城市变化 */
    handleFormCityChange() {
      this.form.district = null
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        province: null,
        city: null,
        district: null,
        roadSiteName: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      // 刷新字典数据，确保获取最新的省市县数据
      this.refreshDictData()
      this.open = true
      this.title = "添加停车道路站点管理"
    },
    /** 刷新字典数据 */
    refreshDictData() {
      // 清除 store 中的字典缓存
      this.$store.dispatch('dict/removeDict', 'province')
      this.$store.dispatch('dict/removeDict', 'city')
      this.$store.dispatch('dict/removeDict', 'area')
      // 重新加载字典数据
      Promise.all([
        getDicts('province'),
        getDicts('city'),
        getDicts('area')
      ]).then(([provinceRes, cityRes, areaRes]) => {
        // 更新 store 中的字典数据
        this.$store.dispatch('dict/setDict', { key: 'province', value: provinceRes.data })
        this.$store.dispatch('dict/setDict', { key: 'city', value: cityRes.data })
        this.$store.dispatch('dict/setDict', { key: 'area', value: areaRes.data })
        // 重新初始化字典
        this.$nextTick(() => {
          if (this.dict && this.dict.reloadDict) {
            this.dict.reloadDict('province')
            this.dict.reloadDict('city')
            this.dict.reloadDict('area')
          }
        })
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getSite(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改停车道路站点管理"
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSite(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addSite(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除停车道路站点管理编号为"' + ids + '"的数据项？').then(function() {
        return delSite(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('parking/site/export', {
        ...this.queryParams
      }, `site_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
